<?php
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

// include libs
require 'libs/facebook.php';
require 'libs/tmhOAuth.php';
require 'libs/tmhUtilities.php';

//load configuration
require 'wsConfig.php';

/**
 * WsSocialManager
 * Implementation de la classe permettant la gestion des messages
 * 
 * @see GNU Public License (GPL)
 * @author Alice Khammy, Leticia Mahammad, Mourad Nedjahi
 * @version 0.621
 *
 * 15 mai 2012
 */
class WsSocialManager {
    
    /**
     * ws params
     */
    private $count = COUNT;
    private $format = FORMAT;
    
    /**
     * facebook params
     */
    private $userId = FB_USERID;
    private $appId = FB_APPID;
    private $secret = FB_SECRET;
    
    /**
     * twitter params
     */
    private $twUser = TW_USER;
    private $consumer_key = TW_CONSUMER_KEY;
    private $consumer_secret = TW_CONSUMER_SECRET;
    private $user_token = TW_USER_TOKEN;
    private $user_secret = TW_USER_SECRET;
    
    /**
     * code de la requete http
     * @var string 
     */
    private $http_response_code=null;
    private $facebookApi=null;
    /**
     * constructeur
     * @param string format
     */
    public function __construct(){
        $args = func_get_args();
        switch(count($args)){
            case 1:
                $this->setFormat($count);
                break;
            case 2:
                $this->setFormat($count);
                $this->format = $format;
                break;
        }
        $this->facebookApi = new Facebook(array('appId' => $this->appId, 'secret' =>$this->secret));
    }
    
    /**
     * 
     * @param string $format 
     */
    public function setFormat($format){
        $format = strtolower ($format);
        if($format=="xml" || $format=="json")
            $this->format = $format;
    }
    
    /**
     * initialiser un compte twitter
     * 
     * @param string $twUser
     * @param string $consumer_key
     * @param string $consumer_secret
     * @param string $user_token
     * @param string $user_secret 
     */
    public function setTwiterAccout($twUser, $consumer_key, $consumer_secret, $user_token, $user_secret){
        $this->twUser = $twUser;
        $this->consumer_key = $consumer_key;
        $this->consumer_secret = $consumer_secret;
        $this->user_token = $user_token;
        $this->user_secret = $user_secret;
    }
    
    /**
     * initialise un compte facebook
     * 
     * @param string $userId
     * @param string $appId
     * @param string $secret 
     */
    public function setFacebookAccount($userId, $appId, $secret){
        $this->userId = $userId;
        $this->appId = $userId;
        $this->secret = $userId;
    }
    
    /**
     * return le code HTTP de la derniere requete effectuee
     * @return string
     */
    public function getResponseCode(){
        return $this->http_response_code;
    }

    /**
     * retourne un tableau contenant les messages de tout les reseaux sociaux
     * @return array
     */
    function getFeed() {
        $facebook = $this->getFacebookFeed();
        if($facebook!==false){
            $twitter = $this->getTwitterFeed();
            $messages = array_merge($facebook, $twitter);
            uasort($messages, 'WsSocialManager::compare');
            return array_values($messages);
        }
        
        return null;
    }

    /**
     * envoi un message sur tout les reseaux sociaux
     * @return array
     */
    function sendMessage($title, $message) {
        // TODO: if, twitter account error
        $this->postTwitterFeed($title, $message);
        $this->postFacebookFeed($title, $message);  
        return $this->http_response_code;
    }
    
    /**
     * recupere les messages de facebook et les renvoi sous forme de tableau
     * 
     * @param type $_userId id de l'utilisateur
     * @param type $_appId 
     * @param type $_secret
     * @param type $_limit
     * @param type $_format
     * @return string 
     */
    private function getFacebookFeed() {
        
        $url = 'https://api.facebook.com/method/stream.get?source_ids=' .
                $this->userId . '&access_token=' . $this->facebookApi->getAccessToken() . '&limit=' . $this->count . "&format=$this->format";

        $oXML = simplexml_load_file($url);
        
        if (empty($oXML->error_code)){
            $res = array();
            $profiles = array();

            foreach ($oXML->profiles->profile as $profile) {
                $profiles[(string) $profile->id] = (string) $profile->name;
            }
            
            foreach ($oXML->posts->stream_post as $stream_post) {
                $res[] = array(
                    'type' => 'facebook',
                    'message_id' => (string) $stream_post->post_id,
                    'user_id' => (string) $stream_post->source_id,
                    'name' => $profiles[(string) $stream_post->source_id],
                    'text' => $this->strToUrl((string) $stream_post->message),
                    'like' => $this->strToUrl((string) $stream_post->description),
                    'attachement'=> $stream_post->attachment->name.' '.$this->strToUrl($stream_post->attachment->href),
                    'date' => (string) $stream_post->created_time,
                    'photo'=> ''
                );
            }
            return $res;
        }
        
        $this->http_response_code = $oXML->error_code;
        return false;
    }

    /**
     * recupere une liste de tweets
     * 
     * @return type 
     */
    private function getTwitterFeed() {
        $url = 'http://twitter.com/statuses/user_timeline/' . $this->twUser . '.xml?count=' . $this->count;    
        $oXML = simplexml_load_file($url);
        $this->http_response_code = $http_response_header[0];
        if (empty($oXML->error_code)) {
            $res = array();
            foreach ($oXML->status as $oStatus) {
                $res[] = array(
                    'type' => 'twitter',
                    'message_id' => (string) $oStatus->id,
                    'user_id' => (string) $oStatus->user->id,
                    'name' => (string) $oStatus->user->name,
                    'text' => $this->strToUrl((string) $oStatus->text),
                    'like' => '',
                    'attachement'=>'',
                    'date' => strtotime((string) $oStatus->created_at),
                    'photo'=> (string) $oStatus->user->profile_image_url 
                );
            }
            return $res;
        }
        
        $this->http_response_code = $oXML->error_code;
        return false;
    }

    /**
     * envoie un message sur twitter
     *
     * @param type $tmhOAuth
     * @param type $message 
     */
    private function postTwitterFeed($title, $message) {
        $tmhOAuth = new tmhOAuth(array(
            'consumer_key' => $this->consumer_key,
            'consumer_secret' => $this->consumer_secret,
            'user_token' => $this->user_token,
            'user_secret' => $this->user_secret
        ));
        
        $this->http_response_code = $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array('status' => $message));
        //error_log($this->http_response_code);
    }

    /**
     * envoi un message sur facebook
     *
     * @param type $title
     * @param type $message
     */
    private function postFacebookFeed($title, $message) {

        $resource = curl_init('https://api.facebook.com/method/notes.create');
        curl_setopt($resource, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($resource, CURLOPT_POST, true);
        curl_setopt($resource, CURLOPT_POSTFIELDS, 'access_token=' . 
                $this->facebookApi->getAccessToken() . '&title=' . $title . '&content=' . $message . '&uid=' . $this->userId);

        $page_content = curl_exec($resource);
        $this->http_response_code = curl_getinfo($resource, CURLINFO_HTTP_CODE);

        curl_close($resource);
    }
    
    /**
     * function de callback, utilisee lors du tri
     *
     * @param array $a
     * @param array $b
     * @return int 
     */
    private function compare($a, $b) {
        if ((int) $a['date'] == (int) $b['date']) {
            return 0;
        }

        return (int) $a['date'] > (int) $b['date'] ? -1 : 1;
    }
    
    /**
     * transforme les chaines de caracteres en Url
     * @param type $text
     * @return string 
     */
    function strToUrl($text) {
      $text = preg_replace('#http://[a-z0-9._/-]+#i', '<a href="$0">$0</a>', $text);
      $text = preg_replace('#@([a-z0-9_]+)#i', '@<a href="http://twitter.com/$1">$1</a>', $text);
      $text = preg_replace('# \#([a-z0-9_-]+)#i', ' #<a href="http://search.twitter.com/search?q=%23$1">$1</a>', $text);
      return $text;
    }
}